package com.example.mode.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.mode.R;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

public class SearchWordActivity extends AppCompatActivity {

    private static final String TAG = "SearchWordActivity";
    private static final String API_URL = "https://api.dictionaryapi.dev/api/v2/entries/en/";

    private EditText etSearchWord;
    private Button btnSearch;
    private TextView tvResult;

    private OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_word);

        etSearchWord = findViewById(R.id.et_search_word);
        btnSearch = findViewById(R.id.btn_search);
        tvResult = findViewById(R.id.tv_result);

        // 空值检查
        if (etSearchWord == null || btnSearch == null || tvResult == null) {
            Log.e(TAG, "视图组件获取失败，请检查布局文件");
            throw new RuntimeException("视图组件获取失败，请检查布局文件");
        }

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String word = etSearchWord.getText().toString().trim();
                    if (!word.isEmpty()) {
                        searchWord(word);
                    } else {
                        tvResult.setText("请输入要查询的单词");
                    }
                } catch (Exception e) {
                    Log.e(TAG, "点击查询按钮时出现异常: " + e.getMessage());
                    tvResult.setText("查询过程中出现异常，请稍后再试");
                }
            }
        });
    }

    private void searchWord(String word) {
        Request request = new Request.Builder()
                .url(API_URL + word)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Log.e(TAG, "网络请求失败: " + e.getMessage());
                    tvResult.setText("网络请求失败，请检查网络连接");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    try {
                        JSONArray jsonArray = new JSONArray(responseData);
                        JSONObject firstEntry = jsonArray.getJSONObject(0);
                        JSONArray meanings = firstEntry.getJSONArray("meanings");
                        StringBuilder resultText = new StringBuilder();

                        for (int i = 0; i < meanings.length(); i++) {
                            JSONObject meaning = meanings.getJSONObject(i);
                            String partOfSpeech = meaning.getString("partOfSpeech");
                            resultText.append("词性: ").append(partOfSpeech).append("\n");

                            JSONArray definitions = meaning.getJSONArray("definitions");
                            for (int j = 0; j < definitions.length(); j++) {
                                JSONObject definitionObj = definitions.getJSONObject(j);
                                String definition = definitionObj.getString("definition");
                                resultText.append("释义: ").append(definition).append("\n");

                                if (definitionObj.has("example")) {
                                    String example = definitionObj.getString("example");
                                    resultText.append("例句: ").append(example).append("\n");
                                }
                                resultText.append("\n");
                            }
                        }

                        if (resultText.length() > 0) {
                            runOnUiThread(() -> tvResult.setText(resultText.toString()));
                        } else {
                            runOnUiThread(() -> tvResult.setText("未找到该单词的释义"));
                        }
                    } catch (JSONException e) {
                        runOnUiThread(() -> {
                            Log.e(TAG, "解析 JSON 数据失败: " + e.getMessage());
                            tvResult.setText("解析数据失败，请稍后再试");
                        });
                    }
                } else {
                    runOnUiThread(() -> tvResult.setText("未找到该单词的释义"));
                }
            }
        });
    }
}